import axios from 'axios';
import { getCookie, delCookie } from './cookies';
import { message } from 'antd';
import qs from 'qs';

const baseUrl = '' // dev
// const baseUrl = 'https://test.boss.api.loong.ph'

// const ishttps = 'https:' === document.location.protocol ? true : false;
// if (ishttps) {
//   const baseUrl = 'https://test.boss.api.loong.ph'
// } else {
//   const baseUrl = 'http://test.boss.api.loong.ph'
// }

const http = {
  get(repo, param) {
    return new Promise((resolve, reject) => {
      axios.get(baseUrl + repo, { headers: { 'token': getCookie('TOKEN') }, params: param})
      .then((response) => {
        if (response.status === 200) {
          const res = response.data;
          switch (res.code) {
            case "00":
              resolve(res);
              break;
            case "01":
              console.log('未授权');
              break;
            default:
          }
        }
      })
      .catch((error) => {
        return resolve(error);
      })
    })
  },

  loginPost(repo, param) {
    return new Promise((resolve, reject) => {
      axios.post(baseUrl + repo, param)
      .then((response) => {
        if (response.status === 200) {
          const res = response.data;
          if (res.code === '00') {
            resolve(res);
          }
        } else {

        }
      })
      .catch((error) => {
        return resolve(error);
      })
    })
  },

  post(repo, param) {
    return new Promise((resolve, reject) => {
      axios.post(baseUrl + repo, param, {
        headers: {
            'token': getCookie('TOKEN')
        },
      })
      .then((response) => {
        if (response.status === 200) {
          const res = response.data;
          resolve(res);
          if (!res.success) {
            message.error(res.message)
            if (res.message === '请登录') {
              delCookie('TOKEN');
              window.location.href = "/login"
            }
          }
        } else {

        }
      })
      .catch((error) => {
        return resolve(error);
      })
    })
  },

  postString(repo, param) {
    return new Promise((resolve, reject) => {
      axios.post(baseUrl + repo, qs.stringify(param), {
        headers: {
            'token': getCookie('TOKEN')
        },
      })
      .then((response) => {
        if (response.status === 200) {
          const res = response.data;
          if (res.code === '00') {
            resolve(res);
          }
        } else {

        }
      })
      .catch((error) => {
        return resolve(error);
      })
    })
  },
}

export default http;
